<template>
  <div>
    <n-row>
      <input ref="file" type="file"/>
    </n-row>
    <n-row style="margin-top: 12px">
      <n-space>
        <n-button type="primary" @click="handleReadContent">Read File</n-button>
        <n-button type="primary" @click="handleClick">Export Data</n-button>
      </n-space>
    </n-row>
    <code style="white-space: pre">{{ content }}</code>
  </div>
</template>
<script setup>
import Exceljs from "exceljs";
import * as ExcelJS from "exceljs";
import dayjs from "dayjs";
import {ref, useTemplateRef} from "vue";

const fileEl = useTemplateRef("file");

const content = ref();

const handleReadContent = () => {
  const file = fileEl.value.files[0];
  if (!file) {
    return;
  }
  const reader = new FileReader();
  reader.addEventListener("load", (event) => content.value = event.target.result);
  reader.readAsText(file)
}

const handleClick = async () => {
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet("Default Sheet");

  sheet.columns = [
    {header: 'Id', key: 'id', width: 10},
    {header: 'Name', key: 'name', width: 32},
    {header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1}
  ]

  const rows = [
    {id: 5, name: 'Bob', DOB: dayjs().format("YYYY-MM-DD HH:mm:ss")},
    {id: 6, name: 'Barbara', DOB: dayjs().format("YYYY-MM-DD HH:mm:ss")}
  ];

  sheet.addRows(rows);
  const buffer = await workbook.xlsx.writeBuffer({filename: "导出数据"});

  const url = URL.createObjectURL(new Blob([buffer]));
  const a = document.createElement("a");
  a.setAttribute("download", "导出数据.xlsx");
  a.href = url;
  a.click();
}

</script>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
